import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useUserStore = defineStore('user', () => {
  const user = ref(JSON.parse(localStorage.getItem('newsUser')) || null);
  const isAuthenticated = ref(!!localStorage.getItem('newsToken'));
  
  // 注册新用户
  const register = (userData) => {
    return new Promise((resolve, reject) => {
      try {
        // 模拟API请求延迟
        setTimeout(() => {
          // 检查用户名是否已存在
          const users = JSON.parse(localStorage.getItem('newsUsers') || '[]');
          const exists = users.some(u => u.username === userData.username);
          
          if (exists) {
            reject({ message: '用户名已被使用' });
            return;
          }
          
          // 创建新用户
          const newUser = {
            id: Date.now(),
            ...userData,
            favorites: [],
            createdAt: new Date().toISOString()
          };
          
          users.push(newUser);
          localStorage.setItem('newsUsers', JSON.stringify(users));
          
          // 自动登录
          login({ username: userData.username, password: userData.password })
            .then(resolve)
            .catch(reject);
        }, 800);
      } catch (error) {
        reject(error);
      }
    });
  };
  
  // 用户登录
  const login = (credentials) => {
    return new Promise((resolve, reject) => {
      try {
        // 模拟API请求延迟
        setTimeout(() => {
          const users = JSON.parse(localStorage.getItem('newsUsers') || '[]');
          const foundUser = users.find(
            u => u.username === credentials.username && 
                 u.password === credentials.password
          );
          
          if (foundUser) {
            // 更新状态
            user.value = foundUser;
            isAuthenticated.value = true;
            
            // 存储到本地
            localStorage.setItem('newsToken', 'user-authenticated');
            localStorage.setItem('newsUser', JSON.stringify(foundUser));
            
            resolve(foundUser);
          } else {
            reject({ message: '用户名或密码不正确' });
          }
        }, 800);
      } catch (error) {
        reject(error);
      }
    });
  };
  
  // 用户登出
  const logout = () => {
    user.value = null;
    isAuthenticated.value = false;
    localStorage.removeItem('newsToken');
    localStorage.removeItem('newsUser');
  };
  
  // 更新用户收藏
  const updateUserFavorites = (userId, favorites) => {
    const users = JSON.parse(localStorage.getItem('newsUsers') || '[]');
    const userIndex = users.findIndex(u => u.id === userId);
    
    if (userIndex !== -1) {
      users[userIndex].favorites = favorites;
      localStorage.setItem('newsUsers', JSON.stringify(users));
      
      // 更新当前用户
      if (user.value && user.value.id === userId) {
        user.value.favorites = [...favorites];
        localStorage.setItem('newsUser', JSON.stringify(user.value));
      }
    }
  };
  
  return {
    user,
    isAuthenticated,
    register,
    login,
    logout,
    updateUserFavorites
  };
});